package com.ocss.ocssservice.controller;/*
@author yuxin
@version 1.0
*/

import com.alibaba.fastjson.JSONObject;
import com.ocss.ocssservice.entity.JsonResult;
import com.ocss.ocssservice.entity.Server;
import com.ocss.ocssservice.entity.ServerRO;
import com.ocss.ocssservice.service.ServerService;
import com.ocss.ocssservice.service.ex.ServerNotFoundException;
import com.ocss.ocssservice.util.JwtUtil;
import com.ocss.ocssservice.util.RedisSave;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("server")
public class ServerController extends BaseController {
    @Autowired
    ServerService serverService;
    @Autowired
    RedisSave redisSave;
    @RequestMapping(value = "/")
    public String homePage() {
        return "login";
    }
    @PostMapping("login")
    @ResponseBody
    public String login(@RequestBody Server server,
                        HttpSession session){
        if(server == null){
            throw new ServerNotFoundException("传来的用户为空");
        }
        Server ser = serverService.selectServerByIdAndPassword(server.getServerId(),server.getPassWord());
        System.out.println(ser);
        JsonResult<ServerRO> result =new JsonResult<>();
        if(ser != null){
            session.setAttribute("serverId", ser.getServerId());
//            session.setAttribute("");
            String token = JwtUtil.sign(ser.getServerId(), ser.getPassWord());
            token = token.substring(0,20);
            result.setState(2000);
            ServerRO serverRO = new ServerRO();
            serverRO.setToken(token);
            serverRO.setServerId(ser.getServerId());
            serverRO.setPassWord(ser.getPassWord());
            serverRO.setName(ser.getName());
            result.setData(serverRO);
            result.setMessage("成功登陆");
            redisSave.saveServerId(token,ser.getServerId());
            return JSONObject.toJSONString(result);
        }
        result.setMessage("失败");
        result.setState(2010);
        return JSONObject.toJSONString(result);
    }

    @RequestMapping("AutoReply")
    @ResponseBody
    public void  changeAutoReply(String serverId,String autoReply){
        Server server = serverService.selectServerById(serverId);
        server.setAutoReply(autoReply);
//        System.out.println(ServerAutoReply.autoReply);
    }
}
